package com.zwcl.common.web.utils;

import com.alibaba.fastjson.JSONObject;
import com.zwcl.common.core.constant.CacheConstants;
import com.zwcl.common.core.domain.entity.CacheUser;
import com.zwcl.common.core.exception.BaseException;
import com.zwcl.common.core.utils.JsonUtils;
import com.zwcl.common.core.utils.StringUtilsEx;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 获取当前用户的服务
 */
@Slf4j
@Component
public class GetLoginUserService {

    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> sops;

    public CacheUser getUserFromHead(HttpServletRequest request) {
        String token = getToken(request);
        try{
            if(!StringUtils.isBlank(token)) {
                CacheUser sysUser = getCurrentUser(token);
                return sysUser;
            }
            return null;
            //还需要获取人事等信息
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getToken(HttpServletRequest request) {
        String  token = request.getHeader(CacheConstants.HEADER);
        if (StringUtilsEx.isNotEmpty(token) && token.startsWith(CacheConstants.TOKEN_PREFIX)){
            token = token.replace(CacheConstants.TOKEN_PREFIX, "");
        }
        return token;
    }


    private CacheUser getCurrentUser(String token) throws BaseException {
        // 从缓存中取login_tokens:token的数据
        String userRedisJson = sops.get(getTokenKey(token));
        if(!StringUtils.isBlank(userRedisJson)) {
            CacheUser sysUser = JsonUtils.jsonToPojo(userRedisJson, CacheUser.class);
            return sysUser;
        }
        return null;
    }

    private String getTokenKey(String token){
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }


}
